<?php


namespace App\Model\User;


use App\Dao\User\UserAccountDao;
use App\Library\User\UserInvitationCode;
use App\Model\File;
use App\Model\Merchant\Merchant;
use App\Model\Model;
use Brick\Math\BigInteger;
use Brick\Math\RoundingMode;
use Hyperf\Database\Model\SoftDeletes;
use Hyperf\Snowflake\Concern\Snowflake;

class User extends Model
{

    protected $table = 'user';

    protected $primaryKey = 'uid';

    protected $appends = [
        'images',
        'invite_code',
        'task_pass_rate',
        'now_money',
    ];

    protected $fillable = [
        'uid',
        'task_pass_num',
        'refresh_num',
        'task_submit_num',
        'top_num',
        'ocean_fish_num',
        'is_spread',
        'ocean_power',
        'send_rubbish_time',
        'ocean_point',
    ];


    public function getTaskPassRateAttribute()
    {
        return $this->checkAttributes(['task_pass_num', 'task_submit_num'], function ($task_pass_num, $task_submit_num) {
            return $task_submit_num == 0 ? 100 : BigInteger::of($task_pass_num)->dividedBy($task_submit_num, 2, RoundingMode::HALF_UP);
        });
    }

    public function getNowMoneyAttribute()
    {
        return $this->checkAttributes('integral', function ($integral) {
            return bcdiv($integral, 10, 2);
        });
    }

    public function getInviteCodeAttribute()
    {
        return $this->checkAttributes('id', function ($id) {
            return UserInvitationCode::init($id);
        });
    }

    public function getIdAttribute($value)
    {
        return (string)$value;
    }

    public function merchant()
    {
        return $this->hasOne(Merchant::class, 'id', 'mer_id');
    }

    public function productDownload()
    {
        return $this->hasOne(ProductDownload::class, 'product_id', 'id');
    }


    public function getImagesAttribute()
    {
        return $this->checkAttributes('images_id', function ($value) {
            return getFilePath(explode(',', $value));
        });

    }

    public function image()
    {
        return $this->hasOne(File::class, 'id', 'image_id');
    }

    public function productContent()
    {
        return $this->hasOne(ProductContent::class, 'product_id', 'id');
    }

    public function userAccount()
    {
        return $this->hasMany(UserAccount::class, 'user_id', 'id');
    }


}